package com.jlf.tool.validation.constraint;

import com.jlf.tool.validation.FieldCompare;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.ObjectUtils;
import org.joor.Reflect;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 字段比较校验器
 *
 * @author wujr
 * 2022/8/15
 * @version 1.0
 * 【变更历史】
 * [wujr 2022/8/15 1.0 新增]
 */
public class FieldCompareValidator implements ConstraintValidator<FieldCompare, Object> {
    private String beginField;
    private String endField;
    private boolean includeEqual;

    @Override
    public void initialize(FieldCompare constraintAnnotation) {
        this.beginField = constraintAnnotation.beginField();
        this.endField = constraintAnnotation.endField();
        this.includeEqual = constraintAnnotation.includeEqual();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        Object beginValue = Reflect.on(value).get(beginField);
        Object endValue = Reflect.on(value).get(endField);
        if (ObjectUtils.isNotEmpty(beginValue) && ObjectUtils.isNotEmpty(endValue)){
            int v = 0;
            if (beginValue instanceof String){
                v = ObjectUtils.compare((String)beginValue, (String)endValue);
            }else if (beginValue instanceof Date){
                v = ObjectUtils.compare((Date)beginValue, (Date)endValue);
            }else if (beginValue instanceof Integer){
                v = ObjectUtils.compare((Integer)beginValue, (Integer)endValue);
            }else if (beginValue instanceof Long){
                v = ObjectUtils.compare((Long)beginValue, (Long)endValue);
            }else if (beginValue instanceof Short){
                v = ObjectUtils.compare((Short)beginValue, (Short)endValue);
            }else if (beginValue instanceof Byte){
                v = ObjectUtils.compare((Byte)beginValue, (Byte)endValue);
            } else if (beginValue instanceof BigDecimal){
                v = ObjectUtils.compare((BigDecimal)beginValue, (BigDecimal)endValue);
            }
            if (includeEqual){
                return v <= 0;
            }else{
                return v < 0;
            }
        }
        return true;
    }
}
